package org.kfish.framework.helper;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Map.Entry;

import org.kfish.framework.annotation.Inject;
import org.kfish.framework.util.ArrayUtil;
import org.kfish.framework.util.MapUtil;
import org.kfish.framework.util.ReflectionUtil;

/**
 * 依赖注入 helper
 * @author CK
 *
 */
public class IocHelper {

	static {
		//获取bean map
		Map<Class<?>,Object> beanMap = BeanHelper.getBeanMap();
		if(MapUtil.isNotEmpty(beanMap)){
			for(Entry<Class<?>,Object> entry:beanMap.entrySet()){
				
				Class<?> beanClass = entry.getKey();
				Object beanInstance = entry.getValue();
				
				//获取bean class 中定义的所有成员变量
				Field[] beanFields = beanClass.getFields();
				if(ArrayUtil.isNotEmpty(beanFields)){
					for(Field beanField:beanFields){
						//字段是否带有注解 @Inject
						if(beanField.isAnnotationPresent(Inject.class)){
							//获取字段类型，进而获取其实例
							Class<?> beanFieldClass = beanField.getType();
							Object beanFieldInstance = ReflectionUtil.newInstance(beanFieldClass);
							//对该成员变量进行初始化
							if(beanFieldInstance!=null){
								ReflectionUtil.setField(beanInstance, beanField, beanFieldInstance);
							}else{
								throw new RuntimeException("can not create instance of class: "+beanFieldClass);
							}
						}
						
					}
				}
				
			}
		}
		
	}
}
